package vn.hanelsoft.openwifi.control;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

import vn.hanelsoft.openwifi.R;
import vn.hanelsoft.openwifi.common.ConstCommon;
import vn.hanelsoft.openwifi.common.UtilsCommon;
import vn.hanelsoft.openwifi.common.network_service.utils.NetworkUtil;
import vn.hanelsoft.openwifi.model.delegate.ServerDelegate;
import vn.hanelsoft.openwifi.model.handler.DatabaseHandler;
import vn.hanelsoft.openwifi.model.object.ObjectFacebook;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager.LayoutParams;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

@SuppressWarnings("deprecation")
public class HomeActivity extends Activity implements OnClickListener {

	Context mContext;
	Intent intent;

	Button btnFreeWifi, btnMapWifi, btnOpenYourWifi;
	boolean checkDisconnectWifi = true;
	Dialog dialog;

	PopupWindow mPopupWindow;
	ImageView imageViewAdvertiser;
	int imgResourceAdvertiser, totalShowImageAdvertiser;

	// for facebook
	String access_token;
	ObjectFacebook mObjectFacebook;

	private Facebook facebook;
	private AsyncFacebookRunner mAsyncRunner;
	private SharedPreferences mPrefs;

	private AdView mAdView;

	boolean isClickAds = false;
	Intent mIntentKillService;
	private TextView mTextDown;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_home);
		ConstCommon.totalTimeService = -1;
		addViewAds();
		mIntentKillService = new Intent(getApplicationContext(),
				KillService.class);
		startService(mIntentKillService);
		initDB();
		initView();
		initDatabase();
		
		mThread.start();
		
		mTextDown.setTypeface(UtilsCommon.getFontCustom(this));
	}

	Thread mThread = new Thread(new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (true) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						setTextDown();
					}
				});
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	});

	void setTextDown() {
		String strMinuter = "";
		String strSecond = "";
		String strTime = "";
		if (ConstCommon.isServiceRunning) {
			if (ConstCommon.minuterService > 9)
				strMinuter += ConstCommon.minuterService;
			else
				strMinuter += "0" + ConstCommon.minuterService;
			if (ConstCommon.secondService> 9)
				strSecond += ConstCommon.secondService;
			else
				strSecond += "0" + ConstCommon.secondService;
			strTime = strMinuter + ":" + strSecond;
		}
		
		mTextDown.setText(strTime);
	}

	void initDatabase() {
		try {
			DatabaseHandler dbHandler = new DatabaseHandler(this);
			dbHandler.createDataBase();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.btnFreeWifi:
			// if (NetworkUtil.checkNetWork(mContext)) {
			checkDisconnectWifi = false;
			intent = new Intent(mContext, FreeWifiActivity.class);
			// intent = new Intent(mContext, ChromeBrowserActivity.class);
			startActivity(intent);
			overridePendingTransition(
					R.drawable.activity_transaction_trans_left_in,
					R.drawable.activity_transaction_trans_left_out);
			// } else {
			// Toast.makeText(mContext,
			// mContext.getString(R.string.not_connect_internet),
			// Toast.LENGTH_LONG).show();
			// }
			break;

		case R.id.btnMapWifi:
			if (NetworkUtil.checkNetWork(mContext)) {
				checkDisconnectWifi = false;
				intent = new Intent(mContext, MapWifiActivity.class);
				startActivity(intent);
				overridePendingTransition(
						R.drawable.activity_transaction_trans_left_in,
						R.drawable.activity_transaction_trans_left_out);
			} else {
				Toast.makeText(mContext,
						mContext.getString(R.string.not_connect_internet),
						Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.btnOpenYourWifi:
			if (NetworkUtil.checkNetWork(mContext)) {
				checkDisconnectWifi = false;
				loginToFacebook();
				
			} else {
				Toast.makeText(mContext,
						mContext.getString(R.string.not_connect_internet),
						Toast.LENGTH_LONG).show();
			}
			break;

		default:
			break;
		}

	}

	@Override
	protected void onStart() {
		Log.d("Luong", "========================== onStart()");
		if (ConstCommon.totalTimeService > 0) {
			ConstCommon.totalTimeService = -1;
			try {
//				stopService(mIntentKillService);
//				unbindService((ServiceConnection) mIntentKillService);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

		super.onStart();
	}

	@Override
	protected void onStop() {
		if (checkDisconnectWifi == false) {
			checkDisconnectWifi = true;
		} else if (isClickAds) {
			isClickAds = false;
			if (ConstCommon.isServiceRunning) {
				if (ConstCommon.isFirst){
					ConstCommon.totalSecondService = (ConstCommon.minuterFirst * 60 - (ConstCommon.minuterService * 60 + ConstCommon.secondService));
					ConstCommon.isFirst = false;
				}
				else
					ConstCommon.totalSecondService = (ConstCommon.minuterWait * 60 - (ConstCommon.minuterService * 60 + ConstCommon.secondService));
				ConstCommon.minuterService = ConstCommon.minuterWait;
				ConstCommon.secondService = 0;
				ServerDelegate.updateTotalTimeShowAd(null, UtilsCommon
						.getStringSetting(getBaseContext(),
								ConstCommon.KEY_WIFI_STORE), String
						.valueOf(ConstCommon.totalSecondService));
			}
		} else {
			//
			if (ConstCommon.isServiceRunning) {
				if (ConstCommon.isFirst){
					ConstCommon.totalSecondService = (ConstCommon.minuterFirst * 60 - (ConstCommon.minuterService * 60 + ConstCommon.secondService));
					ConstCommon.isFirst = false;
				}
				else
					ConstCommon.totalSecondService += (ConstCommon.minuterWait * 60 - (ConstCommon.minuterService * 60 + ConstCommon.secondService));
				ConstCommon.minuterService = ConstCommon.minuterFirst;
				ConstCommon.secondService = 0;
			}
			ServerDelegate.updateTotalTimeShowAd(mhandler, UtilsCommon
					.getStringSetting(getBaseContext(),
							ConstCommon.KEY_WIFI_STORE), String
					.valueOf(ConstCommon.totalSecondService));
			ConstCommon.totalSecondService = 0;
			ConstCommon.isServiceRunning = false;
			UtilsCommon.setStringSetting(getBaseContext(), ConstCommon.KEY_WIFI_STORE, "");
			Log.i("Service1", "Kill");
		}
		super.onStop();
//		Log.d("Luong", "========================== onStop()");
//		if (checkDisconnectWifi == false) {
//			checkDisconnectWifi = true;
//		} else if (isClickAds) {
//			isClickAds = false;
//		} else {
//			UtilsCommon.disConnectWifi(this);
//		}
//		super.onStop();
	}

	Handler mhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 0) {
				UtilsCommon.killApp(getApplicationContext());
			}
		}
	};

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		facebook.authorizeCallback(requestCode, resultCode, data);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onPause() {
		mAdView.pause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mAdView.resume();
	}

	@Override
	protected void onDestroy() {
		mAdView.destroy();
		stopService(mIntentKillService);
		mIntentKillService = null;
		super.onDestroy();
	}

	/*-------------------------- Custom Function -----------------*/

	void addViewAds() {
		mAdView = (AdView) findViewById(R.id.adView);
		mAdView.loadAd(new AdRequest.Builder().build());
		mAdView.setAdListener(new AdListener() {

			@Override
			public void onAdOpened() {
				super.onAdOpened();
				isClickAds = true;
				ServerDelegate.updateTotalTimeClickAd(null, UtilsCommon
						.getStringSetting(getBaseContext(),
								ConstCommon.KEY_WIFI_STORE));
//				if(ConstCommon.isServiceRunning){
//					if(ConstCommon.totalSecondService == 0)
//						ConstCommon.totalSecondService = (ConstCommon.minuterFirst*60 - (ConstCommon.minuterService*60+ConstCommon.secondService));
//					else
//						ConstCommon.totalSecondService = (ConstCommon.minuterWait*60 - (ConstCommon.minuterService*60+ConstCommon.secondService));
//					ConstCommon.minuterService = ConstCommon.minuterWait;
//					ConstCommon.secondService = 0;
//					ServerDelegate.updateTotalTimeShowAd(null, UtilsCommon
//							.getStringSetting(getBaseContext(),
//									ConstCommon.KEY_WIFI_STORE), String
//							.valueOf(ConstCommon.totalSecondService));
//				}
			}

			@Override
			public void onAdLoaded() {
				super.onAdLoaded();
			}

		});
	}

	void initDB() {
		UtilsCommon.turnGPSOn(this);
		mContext = this;
		checkDisconnectWifi = true;
		UtilsCommon.setStringSetting(mContext, ConstCommon.KEY_WIFI_STORE, "");
		facebook = new Facebook(mContext.getString(R.string.app_id));
		mAsyncRunner = new AsyncFacebookRunner(facebook);
		imgResourceAdvertiser = 0;
		totalShowImageAdvertiser = 0;
	}

	void initView() {
		btnFreeWifi = (Button) findViewById(R.id.btnFreeWifi);
		btnFreeWifi.setTypeface(UtilsCommon.getFontCustom(mContext));
		btnFreeWifi.setOnClickListener(this);

		btnMapWifi = (Button) findViewById(R.id.btnMapWifi);
		btnMapWifi.setTypeface(UtilsCommon.getFontCustom(mContext));
		btnMapWifi.setOnClickListener(this);

		btnOpenYourWifi = (Button) findViewById(R.id.btnOpenYourWifi);
		btnOpenYourWifi.setTypeface(UtilsCommon.getFontCustom(mContext));
		btnOpenYourWifi.setOnClickListener(this);

		mTextDown = (TextView) findViewById(R.id.chrome_text_time_down);
	}

	// Facebook
	public void loginToFacebook() {

		mPrefs = getPreferences(MODE_PRIVATE);
		String access_token = mPrefs.getString("access_token", null);
		long expires = mPrefs.getLong("access_expires", 0);
		if (access_token != null) {
			facebook.setAccessToken(access_token);
			getProfileInformation();
		}

		if (expires != 0) {
			facebook.setAccessExpires(expires);
		}

		if (!facebook.isSessionValid()) {
			facebook.authorize(this,
					new String[] { "email", "publish_stream" },
					new DialogListener() {

						@Override
						public void onCancel() {
							// Function to handle cancel event
						}

						@Override
						public void onComplete(Bundle values) {
							SharedPreferences.Editor editor = mPrefs.edit();
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();
							getProfileInformation();
						}

						@Override
						public void onError(DialogError error) {
							// Function to handle error

						}

						@Override
						public void onFacebookError(FacebookError fberror) {
							// Function to handle Facebook errors

						}
					});
		}
	}

	void getProfileInformation() {
		checkDisconnectWifi = false;

		showpopup();

		if (dialog == null || dialog.isShowing() == false) {
			dialog = new Dialog(this);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.dialog_loading);
			dialog.show();
		}
		mAsyncRunner.request("me", new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				// Log.d("Luong",
				// "========================================profile: "+response);
				String json = response;
				try {
					// Facebook Profile JSON data
					JSONObject profile = new JSONObject(json);

					// getting name of the user
					String facebookId = "";
					String name = "";
					String email = "";

					try {
						facebookId = profile.getString("id");
					} catch (Exception e) {
						// TODO: handle exception
					}
					try {
						name = profile.getString("name");
					} catch (Exception e) {
						// TODO: handle exception
					}
					try {
						email = profile.getString("email");
					} catch (Exception e) {
						// TODO: handle exception
					}

					mObjectFacebook = new ObjectFacebook();
					mObjectFacebook.setFacebookId(facebookId);
					mObjectFacebook.setName(name);
					// mObjectFacebook.setSrcImage("http://graph.facebook.com/"
					// + facebookId + "/picture?type=small");

					while (totalShowImageAdvertiser < 3) {
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
						}
					}

					if (totalShowImageAdvertiser >= 3) {
						runOnUiThread(new Runnable() {

							@Override
							public void run() {

								if (dialog.isShowing()) {
									dialog.dismiss();
								}

								if (mPopupWindow != null
										&& mPopupWindow.isShowing()) {
									mPopupWindow.dismiss();
								}
								totalShowImageAdvertiser = 0;
								checkDisconnectWifi = false;
								intent = new Intent(mContext,
										OpenWifiActivity.class);
								intent.putExtra(ConstCommon.KEY_FACEBOOK,
										mObjectFacebook);
								startActivity(intent);
								overridePendingTransition(
										R.drawable.activity_transaction_trans_left_in,
										R.drawable.activity_transaction_trans_left_out);
							}
						});
					}

				} catch (JSONException e) {
				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});
	}

	private void showpopup() {
		if (mPopupWindow == null || mPopupWindow.isShowing() == false) {
			LayoutInflater inflater = this.getLayoutInflater();
			View mView = inflater.inflate(R.layout.popup_advertiser, null);
			imageViewAdvertiser = (ImageView) mView.findViewById(R.id.img);
			mPopupWindow = new PopupWindow(mView, LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT, false);
			mPopupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
			mPopupWindow.showAtLocation(mView, Gravity.CENTER, 0, 0);

			new Thread(new Runnable() {

				@Override
				public void run() {
					while (mPopupWindow != null && mPopupWindow.isShowing()) {
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								if (imgResourceAdvertiser == 0) {
									imgResourceAdvertiser = R.drawable.img_advertiser;
								}
								if (imgResourceAdvertiser == R.drawable.img_advertiser) {
									imgResourceAdvertiser = R.drawable.img_advertiser2;
								} else if (imgResourceAdvertiser == R.drawable.img_advertiser2) {
									imgResourceAdvertiser = R.drawable.img_advertiser3;
								} else if (imgResourceAdvertiser == R.drawable.img_advertiser3) {
									imgResourceAdvertiser = R.drawable.img_advertiser;
								}
								totalShowImageAdvertiser++;
								imageViewAdvertiser
										.setBackgroundResource(imgResourceAdvertiser);
							}
						});
						try {
							Thread.sleep(3000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}).start();
		}
	}
	
}
